<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="期初单号">
              <el-input v-model="form.code" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="仓库">
              <el-input v-model="form.warehouseName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="19">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注">
              <el-input v-model="form.remarks" style="width:75%" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-toolbar id="toolbar_demo3">
      <template v-slot:buttons>
        <el-button @click="insertEvent">新增明细</el-button>
      </template>
    </vxe-toolbar>

    <vxe-table
        border
        resizable
        keep-source
        show-overflow
        ref="xTable"
        :align="allAlign"
        :data="tableData"
        :edit-rules="validRules"
        height="500"
        show-footer
        @scroll="scrollEvent"
        @cell-click="cellClickEvent"
        @edit-actived="editActivedEvent"
        :edit-config="{trigger: 'click', mode: 'cell'}"
      >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="shipmentName" title="入驻商" min-width="150" :edit-render="{}">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.shipmentCode" placeholder="请选择入驻商" style="width:100%" :disabled="Disabled" @change="changeShipment($event, row)">
            <el-option
              v-for="item in shipmentData"
              :key="item.partyCode"
              :label="item.shipmentName"
              :value="item.partyCode"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column field="warehouseSpaceName" title="库区" min-width="200" :edit-render="{}">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.warehouseSpaceCode" placeholder="请选择库区" style="width:100%" :disabled="Disabled" @change="changeWarehouseSpace($event, row)">
            <el-option
              v-for="item in spaceData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column field="locationName" title="库位" min-width="200" :edit-render="{}">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.location" placeholder="请选择库位" style="width:100%" :disabled="Disabled" @change="changeLocation($event, row)">
            <el-option
              v-for="item in locationData"
              :key="item.code"
              :label="item.serialNumber"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <!-- <vxe-table-column field="locationName" title="库位" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <locationElSelect  :val2="form.warehouseCode" :val1="row.warehouseSpaceCode" ref="locationElSelect"  @setLocationCode="setLocationCode(row)" />
        </template>
      </vxe-table-column> -->

      <vxe-table-column field="goodsName" title="商品名称" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <goodsSelect  :val2="row.shipmentCode" :val1="Disabled" ref="goodsSelect"  @setGoodsCode="setGoodsCode(row)" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.goodsUnit" placeholder="请输入单位" style="width:100%" :disabled="Disabled" @change="changeUnit($event, row)">
            <el-option
              v-for="item in row.goodsUnitConversionList"
              :key="item.code"
              :label="item.unitName"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column field="unitQuantity" title="数量" :edit-render="{name: 'input', events: {change: changeEvent}}" width="120"></vxe-table-column>
      <vxe-table-column field="goodsStatusName" title="货品状态"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.goodsStatusName" placeholder="请选择货品状态" style="width:100%" :disabled="Disabled"  @change="goodsStatusNameChangeEvent(row)">
            <el-option
              v-for="item in row.inventoryStatusList"
              :key="item.code"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column field="gmtManufacture" title="生产日期" min-width="150" :edit-render="{name: '$input', props: {type: 'date',disabled: Disabled},attrs: {disabled: Disabled}, events: {change: changeEvent}}"/>
      <vxe-table-column field="gmtExpire" title="过期日期" min-width="150" :edit-render="{name: '$input', props: {type: 'date',disabled: Disabled},attrs: {disabled: Disabled}, events: {change: changeEvent}}"/>
     <!-- <vxe-table-column field="gmtStock" title="存货日期" min-width="150" :edit-render="{name: '$input', props: {type: 'date',disabled: Disabled},attrs: {disabled: Disabled}}"/>-->
      <vxe-table-column field="remarks" title="备注" :edit-render="{name: 'input', events: {change: changeEvent}}" width="270"></vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="50">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="removeRow(scope.row)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitSave" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>提 交</el-button>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  import VXETablePluginElement from 'vxe-table-plugin-element'
  import 'vxe-table-plugin-element/dist/style.css'
  import locationElSelect from '@/views/components/locationElSelect.vue'
  import goodsSelect from '@/views/components/goodsElSelect.vue'
  import { getShipments, getLocationList } from '@/api/basicInfo'
  import { initializationDetail, initializationEdit, getInitializationDetails, shipmentUnitStatus } from '@/api/store'
  import { getWarehouse, getWarehouseSpace } from '@/api/basicInfo'
  import request from '@/utils/request'
  import Qs from 'qs'
  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  VXETable.use(VXETablePluginElement)
  export default {
    name: 'initializationEdit',
    components: {
      goodsSelect,
      locationElSelect
    },
    data() {
      return {
        deleteCodes:[],

        allAlign:'center',
        isDisable:false,   //确定键显示按钮
        tableData: [],
        showShipment: false,
        showLocation: false,
        Disabled: false,
        showOpQuantity: false,
        warehouseData:[],//仓库列表
        shipmentData:[], // 入驻商
        spaceData:[], // 库区
        locationData:[], // 库位
        warehouseSpaceData:[],
        goodsData:[],
        lockList: [
          { value: "0", label: "否" },
          { value: "1",label: "是" },
        ],
        inventoryStatusList: [
        ],
        //盘点类型列表
        countingTypeData:[
          { code: "0", name: "全盘" },
          { code: "1",name: "入驻商盘点" },
          { code: "2",name: "库位盘点" },
          { code: "3",name: "动碰盘点" }
        ],
        form: {
          code:'',                                //数据标识 ,
          name:'',                                //库位名称 ,
          remarks:'',                             //备注 ,
          status:'',                              //状态 ,
          total:'',                               //总数 ,
          warehouseCode:'',                       //所属仓库
          deleteCodes:[],

          supervisor: '',
          opQuantity: '',
          shipmentCode: '',
          shipmentName: '',
          location: '',
          type: '',
          initializationItemList: []
        },
        listQuery: {
          pageNum: 1,
          pageSize: 60,
          total: 0,
          code: this.$route.query.code
        },
        loading: false,
        validRules: {
          unitQuantity: [
            { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数量必须大于0' },
            { max: 10, message: '数量不能超过10位'}
          ],
        },
        rules:{},
        addData:[],
        delData: [],
        editData:[],
        noMoreData: false, // 数据是否全部加载完成
      }
    },
    created() {
      // this.findLocations()
      // this.getWarehouse()
      // this.getShipments()
      this.getList()
      this.shipmentUnitStatus()
    },
    methods: {
      scrollEvent(e) {
        if (e.isY && !this.noMoreData) {
            // 函数防抖
            if (this.timer) {
              clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
              const el = this.$refs.xTable.$el.querySelector('.vxe-table--body-wrapper')
              const num = el.scrollHeight - (el.offsetHeight + el.scrollTop)
              if (num === 0 || num < 100) {
                this.listQuery.pageNum = this.listQuery.pageNum+1
                const rowNum = this.listQuery.pageNum * this.listQuery.pageSize
                this.getList(rowNum)
              }
            }, 600)
        }
      },
      // 获取入驻商列表信息
      getShipments() {
        getShipments()
          .then(res => {
            this.shipmentData = res.data
        })
      },
       // 获取库位列表信息
      findWarehouseSpaces(code) {
        getWarehouseSpace(code).then(response => {
          this.spaceData = response.data
        })
      },
       // 获取库区列表信息
      getLocationList(code) {
        getLocationList(code).then(response => {
          this.locationData = response.data
        })
      },
      // 获取 入驻商、单位、货品状态
      shipmentUnitStatus() {
        shipmentUnitStatus().then(res => {
          this.shipmentData = res.data
        })
      },
       // 获取单位列表信息
      // findUnitByShipmentCode(code) {
      //   findUnitByShipmentCode(code).then(response => {
      //     this.unitData = response.data
      //   })
      // },
      // 获取期初列表数据
      getList() {
        getInitializationDetails(Qs.stringify(this.listQuery))
          .then(res => {
            this.form = res.data,
            this.tableData = [...this.tableData, ...res.data.initializationItemList]
            this.listQuery.total = this.form.total;
            this.findWarehouseSpaces(res.data.warehouseCode)
            this.getLocationList(res.data.warehouseCode)

            if (res.data.initializationItemList.length === 0 || res.data.total <= this.tableData.length) {
              this.noMoreData = true
            }
        })
      },
      // 下拉框更改 - 入驻商
      changeShipment(shipmentCode, row) {
        row.shipmentCode = shipmentCode
        const data = this.shipmentData.filter(item => item.partyCode === shipmentCode )
        row.shipmentName = data[0].shipmentName

        row.goodsUnit = ''
        row.goodsUnitName = ''

        row.goodsStatus = ''
        row.goodsStatusName = ''

        if (row.shipmentCode !== shipmentCode) {
          this.editOperation(row)
        }
      },
      // 下拉框更改 - 库区
      changeWarehouseSpace(code, row) {
        row.warehouseSpaceCode = code
        const data = this.spaceData.filter(item => item.code === code )
        row.warehouseSpaceName = data[0].name
        if (row.warehouseSpaceCode !== code) {
          this.editOperation(row)
        }
      },
      // 下拉框更改 - 库位
      changeLocation(code, row) {
        row.location = code
        const data = this.locationData.filter(item => item.code === code )
        row.locationName = data[0].serialNumber
        if (row.location !== code) {
          this.editOperation(row)
        }
      },
      // 下拉框更改 - 单位
      changeUnit(code, row) {
        const data = row.goodsUnitConversionList.filter(item => item.code === code )
        row.goodsUnit = code;
        row.goodsUnitName = data[0].unitName
        row.unitName = data[0].unitName
        row.basicQuantity = 1
        if (row.goodsUnit !== code) {
          this.editOperation(row)
        }
      },
      // 下拉框更改 - 数量&备注&生产日期&过期日期
      changeEvent(row) {
        this.editOperation(row)
      },

    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
        this.getInfo()

      })
    },
    // 单元格被点击事件
    cellClickEvent (data) {
      if (data.column.property === 'goodsUnitName') {
          const item = this.shipmentData.filter(item => item.partyCode === data.row.shipmentCode )
          data.row.goodsUnitConversionList = item[0].goodsUnitList
      }
      if (data.column.property === 'goodsStatusName') {
          const item = this.shipmentData.filter(item => item.partyCode === data.row.shipmentCode )
          data.row.inventoryStatusList = item[0].inventoryStatusList
      }
    },
    // changeWarehouseSpace({row}){
    //   row.locationName = ''
    //   row.location = ''
    // },
    // 选择仓库
    setWarehouseCode(){
      this.tableData = [];
      this.$refs.xTable.tableData = []
      this.findWarehouseSpaces(this.form.warehouseCode)

      this.findShipments()
    },
    setLocationCode(row){
      let obj = this.$refs.locationElSelect.obj1
      const sd = this.locationData.find(i => i.code == obj)
      row.locationName = sd.serialNumber
      row.location = obj
    },
    //商品选择
    setGoodsCode(row){
      let obj = this.$refs.goodsSelect.obj1
      row.goodsName = obj.name
      row.goodsCode = obj.code
      row.goodCode = obj.goodCode
      row.unitName = obj.unitName
      row.unitCode = obj.unitCode
      row.goodsBarCode = obj.barCode
      row.basicUnit = obj.unitCode;
      row.basicUnitName = obj.basicUnitName;
      row.goodsUnitConversionList = obj.goodsUnitConversionList
      if (row.goodsCode !== obj.code) {
        this.editOperation(row)
      }
    },
      // 单位选择
      selectGoodsUnitCode(event, row){
        row.goodsUnit = event.value;
        row.goodsUnitName = event.label;
        row.unitName = event.label;
        row.basicQuantity = event.basicQuantity;
      },
      // 编辑数据操作
      editOperation(e) {
        if (!e.row.timestamp) {
          e.row.type='edit'
          if (this.editData.length>0) {
            let isEqual = false
            this.editData.forEach((currentValue, index) => {
              if (currentValue.code === e.row.code) {
                // 已经在编辑数据的数组中，需要替换原数据
                this.editData.splice(index,1,e.row)
                isEqual = true
              }
            });
            if (!isEqual) {
              this.editData.push(e.row)
            }
          } else {
            this.editData.push(e.row)
          }
        }
      },
    // 删除行
    removeRow(row){
      this.$confirm('确认删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          if (row.type) {
              this.addData.forEach((item, index)=>{
                if (item.timestamp === row.timestamp) {
                  this.addData.splice(index, 1)
                }
              })
              this.tableData.forEach((item, index)=>{
                if (item.timestamp === row.timestamp) {
                  this.tableData.splice(index, 1)
                }
              })
          } else {
              this.tableData.forEach((item, index)=>{
                if (item.code === row.code) {
                  this.addData.splice(index, 1)
                  item.type = 'delete'
                  this.delData.push(item)
                  this.tableData.splice(index, 1)
                }
              })
          }
          if(row.code !== undefined && row.countingItemCode == undefined){
            this.deleteCodes.push(row.code)
          }
          this.$refs.xTable.remove(row)
        })
        .catch(() => {
          // console.log('已取消，不加catch会报警告')
        })
    },

    // 新增
    insertEvent () {
        // const xTable = this.$refs.xTable
        // xTable.insert().then(({ row }) => xTable.setActiveRow(row))

        const timestamp = new Date().getTime()
        const obj = {timestamp, "basicQuantity":"","basicUnit":"","basicUnitName":"","code":"","createdBy":"","extendFive":"","extendFour":"","extendOne":"","extendSix":"","extendThree":"","extendTwo":"","gmtCreated":"","gmtExpire":"","gmtManufacture":"","gmtModified":"","gmtStock":"","goodCode":"","goodsBarCode":"","goodsCode":"","goodsName":"","goodsStatus":"","goodsStatusName":"","goodsUnit":"","goodsUnitConversionList":[],"goodsUnitName":"","id":"","initializationCode":"","location":"","locationName":"","modifiedBy":"","quantity":"","remarks":"","serialNumber":"","shipmentCode":"","shipmentName":"","supplier":"","unitQuantity":"","warehouseCode":"","warehouseName":"","warehouseSpaceCode":"","warehouseSpaceName":"","type":"add"}
        this.tableData.unshift(obj)
        this.addData.push(obj)
        setTimeout(() => {
          this.$refs.xTable.clearScroll()
        }, 200);
    },
      editActivedEvent ({ row, rowIndex }) {
        this.Disabled = false
      },
      // 获取页面信息
      getInfo() {
        this.loading = true
        let code = this.$route.query.code ? this.$route.query.code : "";

        initializationDetail(code).then(response => {
          this.form = response.data,
          this.tableData = this.form.initializationItemList;
          this.findWarehouseSpaces(response.data.warehouseCode)

          // this.tableData.forEach ( i => {
          //   request({
          //     url: '/wms/inventoryStatus/chooseData',
          //     method: 'get',
          //     params: { shipmentCode: i.shipmentCode}

          //   }).then(response => {
          //    i.inventoryStatusList = response.data
          //   })

          // })
          this.loading = false
          this.findShipments()
        })
      },
      formatterGoodsCode({ cellValue, row }) {
        return row.productCode;
      },
      formatterGoodsUnit({ cellValue, row }) {
        return row.unitName;
      },
      formatterLocation({ cellValue, row }) {
        row.location = row.locationName;
        return row.locationName;
      },
      formatterStatus({ cellValue, row }) {
        row.inventoryCode = row.code;
        if (row.status === '0') {
          return '合格'
        } else if (row.status === '1') {
          return '不合格'
        }
      },
      formatterLock({ cellValue, row }) {
        row.lock = row.lockName;
        if (cellValue === 0) {
          return '否'
        } else if (cellValue === 1) {
          return '是'
        }
      },
      // 保存
      funcSubmitSave() {
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细数据')
        } else {
          if(this.deleteCodes){
              this.form.deleteCodes = this.deleteCodes
          }
          this.form.initializationItemList = [...this.editData, ...this.addData]
          this.form.status = '0';
          const data = this.form;
          this.$refs.xTable.validate((valids) => {
            if (valids) {
              this.isDisable = true;
              initializationEdit(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({
                  path: "/kngl/initializationList"
                });
                this.isDisable = false
              }).catch(() => this.isDisable = false)
            } else {
              return false
            }
          })
        }
      },
      // 提交
      funcSubmitCheck() {
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细数据')
        } else {
          if(this.deleteCodes){
              this.form.deleteCodes = this.deleteCodes
          }

          this.form.initializationItemList = [...this.editData, ...this.addData]
          this.form.status = '1';
          const data = this.form;
          this.$refs.xTable.validate((valids) => {
            if (valids) {
              this.isDisable = true;
              initializationEdit(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({
                  path: "/kngl/initializationList"
                });
                this.isDisable = false
              }).catch(() => this.isDisable = false)
            } else {
              return false
            }
          })
        }
      },
      // 取消
      funcCancel() {
        this.$emit('fatherCancelMethod', 'add')
      },
      findShipments() {
        request({
          url: '/wms/warehouseShipment/business/shipments',
          method: 'get',

        }).then(response => {
          this.shipmentData = response.data
        })
      },
      findGoodsStatus(shipmentCode) {
        let inventoryStatusList = []
        request({
          url: '/wms/inventoryStatus/chooseData',
          method: 'get',
          params: { shipmentCode: shipmentCode}

        }).then(response => {
         inventoryStatusList = response.data
        })
        return inventoryStatusList
      },
    //计算基本单位
    nameChangeEvent (row) {
      const sd = row.goodsUnitConversionList.find(i => i.unitName == row.unitName)
      row.goodsUnit = sd.unitCode
    },
    goodsStatusNameChangeEvent (row) {
      const sd = row.inventoryStatusList.find(i => i.name == row.goodsStatusName)
      row.goodsStatus = sd.code
      row.goodsStatusName = sd.name
      if (row.goodsStatus !== sd.code) {
        this.editOperation(row)
      }
    },
      findLocations() {
        request({
          url: '/wms/location/chooseData',
          method: 'get',

        }).then(response => {
          this.locationData = response.data
        })
      }
    }

  }
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 150px auto;
    width: 175px;
    // float: right;
  }
</style>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }
  .vxe-toolbar{padding:0 0 10px 0}
</style>
